import commonPage from 'clientApi/commonPage.js'
import widget from 'gapi/widget'
import clientInfo from 'gapi/clientInfo.js'
import location from 'clientApi/location.js'
export let getUrddataString = (name) => {
    var params = '?' + decodeURIComponent(decodeURIComponent(window.location.search.substring(9)));
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]")
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(params)
    return results === null ? null : decodeURIComponent(results[1].replace(/\+/g, " "))
}

export let getQueryString = (name) => {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]")
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(window.location.search)
    return results === null ? null : decodeURIComponent(results[1].replace(/\+/g, " "))
}

//日期格式初始化
export let getLocalTime = (unixtime,pattern) => {
    Date.prototype.format = function(pattern){
        var pad = function (source, length) {
            var pre = "",
                negative = (source < 0),
                string = String(Math.abs(source));

            if (string.length < length) {
                pre = (new Array(length - string.length + 1)).join('0');
            }

            return (negative ?  "-" : "") + pre + string;
        };

        if ('string' != typeof pattern) {
            return this.toString();
        }

        var replacer = function(patternPart, result) {
            pattern = pattern.replace(patternPart, result);
        }

        var year    = this.getFullYear(),
            month   = this.getMonth() + 1,
            date2   = this.getDate(),
            hours   = this.getHours(),
            minutes = this.getMinutes(),
            seconds = this.getSeconds();

        replacer(/yyyy/g, pad(year, 4));
        replacer(/yy/g, pad(parseInt(year.toString().slice(2), 10), 2));
        replacer(/MM/g, pad(month, 2));
        replacer(/M/g, month);
        replacer(/dd/g, pad(date2, 2));
        replacer(/d/g, date2);

        replacer(/HH/g, pad(hours, 2));
        replacer(/H/g, hours);
        replacer(/hh/g, pad(hours % 12, 2));
        replacer(/h/g, hours % 12);
        replacer(/mm/g, pad(minutes, 2));
        replacer(/m/g, minutes);
        replacer(/ss/g, pad(seconds, 2));
        replacer(/s/g, seconds);

        return pattern;
    };
    var timestr = new Date(parseInt(unixtime));
    var datetime = timestr.format(pattern);
    return datetime;
}

/**
 * [时间字符串转时间戳]
 * @param  {[String]} dateString [时间字符串，可以有两种格式1：'2016/11/15' 2：'2016-11-15']
 * @return {[Number]} Stamp      [时间戳(毫秒数)]
 */
export let getStampFromDate = (dateString) => {
    dateString = dateString.replace(/-/g, '/')
    let d = new Date(dateString)
    let Stamp = d.getTime()
    return Stamp
}

const api = '/sea/api/1.0/client/v1'

/**
 * 接口请求
 * @method ajax
 * @public
 * @param {JSON} ajaxParam 参数
 * @example
 *      util.ajax({
 *          url: 'path',
 *          data: {},
 *          timeout: 0,
 *          success: function(data){},
 *          error: function(){},
 *          noNetwork: function(){}
 *      })
 * @since 3.0.0
 */
export let ajax = (ajaxParam) => {
    clientInfo.getHost((host) => {
        host = host.info;
        clientInfo.getCommonHeaders(function(data){
            var headersJson = {};
            var key;
            for(let name in data){
                key = name.charAt(0).toUpperCase() + name.substring(1);
                headersJson[key] = data[name];
            }

            clientInfo.getNetworkType((networkData) => {
                if(networkData.network != 'invalid'){
                    // console.log(`${host}${api}${ajaxParam.url}`)
                    // console.log(ajaxParam.data)
                    // 请求 index top 数据
                    $.ajax({
                        url : `${host}${api}${ajaxParam.url}`,
                        timeout : ajaxParam.timeout || 0,
                        headers: headersJson,
                        data: ajaxParam.data || {},
                        dataType: ajaxParam.dataType || 'json',
                        type: ajaxParam.type || 'GET',
                        success: (data) => {
                            ajaxParam.success(data)
                            if(data.errno != 0){
                                console.log('errno != 0 时 调/common/collect/put')
                                console.log('问题接口：'+ajaxParam.url)
                                console.log('入参：'+JSON.stringify(ajaxParam.data))
                                $.ajax({
                                    url:`${host}${api}/common/collect/put`,
                                    headers: headersJson,
                                    data:{
                                        link: `${host}${api}${ajaxParam.url}`,
                                        param: JSON.stringify(ajaxParam.data),
                                        result: JSON.stringify(data)
                                    },
                                    type: "POST",
                                    success: (data) => {
                                        console.log(data)
                                    }
                                })
                            }
                        },
                        error : (xhr, status) => {
                            if(status === 'timeout'){
                                commonPage.loadPageStatus('loadSuccess')
                                widget.toast('网络连接失败，请检查网络')
                            }else{
                                ajaxParam.error(xhr, status)
                            }
                            
                            console.log('走error 调/common/collect/put')
                            console.log('问题接口：'+ajaxParam.url)
                            console.log('入参：'+JSON.stringify(ajaxParam.data))
                            $.ajax({
                                url:`${host}${api}/common/collect/put`,
                                headers: headersJson,
                                data:{
                                    link: `${host}${api}${ajaxParam.url}`,
                                    param: JSON.stringify(ajaxParam.data),
                                    result: JSON.stringify({
                                        xhr: xhr,
                                        status: status
                                    })
                                },
                                type: "POST",
                                success: (data) => {
                                    console.log(data)
                                }
                            })
                        }
                    });

                }else{
                    ajaxParam.noNetwork()
                }
            })
        })
    })
}

/*日期*/
export let formatDate = (unixtime) => {
    if ('Invalid Date' == new Date(unixtime) || unixtime == 0) {
        return '未知';
    }
    unixtime *= 1000;

    let ut_year = getLocalTime(unixtime, "yyyy")
    let ut_month = getLocalTime(unixtime, "MM-dd")
    let ut = ut_year + "-" + ut_month;

    //作为标记的今天、昨天、今年时间戳
    let d = new Date();
    let today = getStampFromDate(d.getFullYear() + "-"+ (d.getMonth()+1) + "-" + d.getDate());
    let yesterday = today - 86400000;
    let year = getStampFromDate(d.getFullYear() + "-01-01");

    // console.log(ut, "today:"+today,"yesterday:"+yesterday, "year:"+year);

    if (unixtime >= today) {//今天
        return getLocalTime(unixtime, "HH:mm");
    } else if (unixtime >= yesterday && unixtime < today) {//昨天
        return '昨天';
    } else if (unixtime < year) {//小于今年
        return ut;
    } else {//昨天之前
        return ut_month;
    }
}
/*钱包日期*/
export let mywalletDate = (unixtime) => {
    if ('Invalid Date' == new Date(unixtime) || unixtime == 0) {
        return '未知';
    }
    unixtime *= 1000;

    let ut_year = getLocalTime(unixtime, "yyyy")
    let ut_month = getLocalTime(unixtime, "MM-dd")
    let ut = ut_year + "-" + ut_month;

    //作为标记的今天、昨天、今年时间戳
    let d = new Date();
    let today = getStampFromDate(d.getFullYear() + "-"+ (d.getMonth()+1) + "-" + d.getDate());
    let yesterday = today - 86400000;
    let year = getStampFromDate(d.getFullYear() + "-01-01");

    //xinjia
    let minute = 1000 * 60;  
    let hour = minute * 60;
    let timePublish = new Date(unixtime);
    let timeNow = new Date(); 
    let diffValue = timeNow - timePublish;
    let diffHour = diffValue / hour; 
    //xinjia

    console.log(12345678+ut, "today:"+today,"yesterday:"+yesterday, "year:"+year);

    if (unixtime >= today) {//今天
        return  parseInt(diffHour) + "小时前";
    }else if (unixtime < year) {//小于今年
        return ut + ' ' + getLocalTime(unixtime, "HH:mm");
    } else {//昨天之前
        return ut_month + ' ' + getLocalTime(unixtime, "HH:mm");
    }
}

/**
 * 页面到底，调用callback
 */
export let scrollPageEnd = (callback) => {
    $(document).ready(function () { //本人习惯这样写了
        $(window).scroll(function () {
            $(window).scrollTop() // 这个方法是当前滚动条滚动的距离
            //$(window).height()获取当前窗体的高度
            //$(document).height()获取当前文档的高度
            var bot = 20; //bot是底部距离的高度
//            console.log("window.scrollTop="+$(window).scrollTop(), "document.height="+$(document).height(), "window.height="+$(window).height());
            if ((bot + $(window).scrollTop()) >= ($(document).height() - $(window).height())) {
                callback();
            }
        });
    });
}
export let OS = () => {
    let os = navigator.userAgent.match(/iphone|ipad|ipod/i) ? "ios" : "android"
    return os
}
export let isIphoneX = () => {
    return /iphone/gi.test(navigator.userAgent) && (screen.height == 812 && screen.width == 375)
}


export let baseImageDomain = 'http://image.doumi.com/'

export let devDomain = 'http://saas-test.doumi.com'

export let apiPathforSaas = '/sea/api/1.0/client/v1'

export let KqMapImg = {
        attendImgN:"",
        attendImgU:"",
        attendImgY:"",
        taskImg:""
}

//切换数字-切换地图  1-百度 2-高德
let mapType = 2
export let requestPOI = function(callback){
    console.log(mapType)
    location.requestPOI(mapType, callback)
    mapType = mapType >= 2 ? 1 : mapType + 1
}

//检查网络
setTimeout(function(){
    clientInfo.getNetworkType((data) => {
        if(data.network == 'invalid' || navigator.onLine == false){
            commonPage.loadPageStatus('loadSuccess');
            widget.toast('网络连接失败，请检查网络');
        }
    })
},5000)
